package com.rongmei.jdsync.util;

import okhttp3.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author dongjun
 */
@Slf4j
public class HttpClientUtil {
    private static final int CONNECT_TIMEOUT = 30;
    private static final int READ_TIMEOUT = 60;
    private static final int WRITE_TIMEOUT = 30;

    /**
     * 创建一个OkHttpClient实例
     *
     * @return 创建的OkHttpClient实例
     */
    public static OkHttpClient createHttpClient() {
        return new OkHttpClient().newBuilder()
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 构建HTTP POST请求
     *
     * @param url 请求的URL
     * @param auth 认证信息
     * @param body 请求体
     * @return 构建好的HTTP POST请求对象
     */
    public static Request buildRequest(String url, String auth, RequestBody body) {
        return new Request.Builder()
                .url(url)
                .method("POST", body)
                .addHeader("authentication", auth)
                .build();
    }

    /**
     * 处理HTTP响应并返回指定类型的对象
     *
     * @param response          HTTP响应对象
     * @param responseType      需要返回的对象类型
     * @param <T>               返回对象的类型
     * @return 指定类型的对象
     * @throws IOException      如果请求失败或JSON解析失败，则抛出IOException异常
     */
    public static <T> T processResponse(Response response, Class<T> responseType) throws IOException {
        if (!response.isSuccessful()) {
            throw new IOException("请求失败: " + response.code() + " - " + response.message());
        }

        String responseBody = response.body().string();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(responseBody, responseType);
        } catch (JsonProcessingException e) {
            log.error("JSON解析失败: {}", e.getMessage(), e);
            throw new IOException("JSON解析失败: " + e.getMessage());
        }
    }

    /**
     * 记录请求完成信息
     *
     * @param operation 操作名称
     * @param dataSize 处理的数据项数量
     * @param startTime 请求开始时间（毫秒）
     */
    public static void logRequestCompletion(String operation, int dataSize, long startTime) {
        log.info("{} 操作完成，处理 {} 条数据，总耗时: {} 毫秒",
                operation, dataSize, System.currentTimeMillis() - startTime);
    }
}